"use client"

import { useState, useEffect } from "react"
import { useParams, useRouter } from "next/navigation"
import { motion } from "framer-motion"
import { 
  ChevronLeft,
  Users, 
  MapPin, 
  Calendar,
  Trophy,
  Star,
  Settings,
  UserPlus,
  MessageCircle,
  Share2,
  Crown,
  Shield,
  User,
  Mail,
  Github,
  Linkedin
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { useAuth } from "@/contexts/auth-context"
import { LoadingScreen } from "@/components/loading-screen"

interface TeamMember {
  id: string
  username: string
  full_name?: string
  avatar_url?: string
  role: "leader" | "admin" | "member"
  skills: string[]
  joined_at: string
  email?: string
  github_url?: string
  linkedin_url?: string
}

interface Team {
  id: string
  name: string
  description: string
  avatar_url?: string
  member_count: number
  max_members: number
  skills: string[]
  location?: string
  created_at: string
  is_recruiting: boolean
  competition_id?: string
  competition_name?: string
  leader_id: string
  members: TeamMember[]
  achievements: string[]
  projects: any[]
}

export default function TeamDetailPage() {
  const params = useParams()
  const router = useRouter()
  const { user, isAuthenticated } = useAuth()
  const [teamData, setTeamData] = useState<Team | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isMember, setIsMember] = useState(false)
  const [isLeader, setIsLeader] = useState(false)

  useEffect(() => {
    const fetchTeam = async () => {
      try {
        setIsLoading(true)
        // TODO: 实现团队详情API调用
        // const response = await teamsApi.getTeam(params.id as string)
        // setTeam(response.data)
        
        // 模拟数据
        const mockTeam: Team = {
          id: params.id as string,
          name: "CodeCrafters",
          description: "我们是一支专注于Web开发和AI应用的团队，致力于创造创新的解决方案。我们正在寻找有经验的前端和后端开发者加入我们，一起参加即将到来的AI创新大赛。",
          avatar_url: "",
          member_count: 3,
          max_members: 5,
          skills: ["React", "Node.js", "Python", "AI", "TypeScript", "PostgreSQL"],
          location: "北京",
          created_at: "2024-01-15T00:00:00Z",
          is_recruiting: true,
          competition_id: "1",
          competition_name: "2024 AI创新大赛",
          leader_id: "1",
          members: [
            {
              id: "1",
              username: "techleader",
              full_name: "张三",
              avatar_url: "",
              role: "leader",
              skills: ["React", "Node.js", "Leadership"],
              joined_at: "2024-01-15T00:00:00Z",
              email: "techleader@example.com",
              github_url: "https://github.com/techleader"
            },
            {
              id: "2",
              username: "frontend_dev",
              full_name: "李四",
              avatar_url: "",
              role: "member",
              skills: ["React", "TypeScript", "CSS"],
              joined_at: "2024-01-16T00:00:00Z",
              email: "frontend@example.com"
            },
            {
              id: "3",
              username: "ai_expert",
              full_name: "王五",
              avatar_url: "",
              role: "member",
              skills: ["Python", "TensorFlow", "AI"],
              joined_at: "2024-01-17T00:00:00Z",
              email: "ai@example.com",
              linkedin_url: "https://linkedin.com/in/aiexpert"
            }
          ],
          achievements: ["最佳团队合作奖", "创新解决方案奖"],
          projects: []
        }
        setTeam(mockTeam)
        
        // 检查用户是否是团队成员
        if (user) {
          const memberExists = mockTeam.members.some(member => member.id === user.id)
          setIsMember(memberExists)
          setIsLeader(mockTeam.leader_id === user.id)
        }
      } catch (error) {
        console.error("Failed to fetch team:", error)
        router.push("/teams")
      } finally {
        setIsLoading(false)
      }
    }

    if (params.id) {
      fetchTeam()
    }
  }, [params.id, router, user])

  const handleJoinTeam = async () => {
    if (!isAuthenticated) {
      router.push("/auth/login")
      return
    }
    
    try {
      // TODO: 实现加入团队的API调用
      console.log("Join team:", team?.id)
    } catch (error) {
      console.error("Failed to join team:", error)
    }
  }

  const handleLeaveTeam = async () => {
    if (!isAuthenticated) return
    
    try {
      // TODO: 实现离开团队的API调用
      console.log("Leave team:", team?.id)
    } catch (error) {
      console.error("Failed to leave team:", error)
    }
  }

  const getRoleIcon = (role: string) => {
    switch (role) {
      case "leader":
        return <Crown className="w-4 h-4 text-yellow-400" />
      case "admin":
        return <Shield className="w-4 h-4 text-blue-400" />
      default:
        return <User className="w-4 h-4 text-gray-400" />
    }
  }

  const getRoleText = (role: string) => {
    switch (role) {
      case "leader":
        return "队长"
      case "admin":
        return "管理员"
      default:
        return "成员"
    }
  }

  if (isLoading) {
    return <LoadingScreen />
  }

  if (!team) {
    return (
      <div className="min-h-screen pt-20 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-white mb-4">团队不存在</h1>
          <Button onClick={() => router.push("/teams")} variant="outline">
            返回团队列表
          </Button>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen pt-20">
      <div className="container mx-auto px-4 py-8">
        {/* 返回按钮 */}
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          className="mb-6"
        >
          <Button
            variant="ghost"
            onClick={() => router.back()}
            className="text-white hover:text-blue-300"
          >
            <ChevronLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
        </motion.div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 团队信息卡片 */}
          <div className="lg:col-span-1">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="space-y-6"
            >
              <Card className="bg-gray-800/50 border-gray-700">
                <CardContent className="p-6">
                  <div className="text-center mb-6">
                    <Avatar className="w-24 h-24 mx-auto mb-4">
                      <AvatarImage src={team.avatar_url || ""} alt={team.name} />
                      <AvatarFallback className="text-2xl bg-gradient-to-r from-blue-500 to-purple-500">
                        {team.name.charAt(0).toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                    <h1 className="text-2xl font-bold text-white mb-2">{team.name}</h1>
                    <div className="flex items-center justify-center gap-2 mb-4">
                      <Badge 
                        variant={team.is_recruiting ? "default" : "secondary"}
                        className={team.is_recruiting ? "bg-green-500/20 text-green-300" : "bg-gray-500/20 text-gray-300"}
                      >
                        {team.is_recruiting ? "招募中" : "已满员"}
                      </Badge>
                    </div>
                    <p className="text-gray-300 text-sm">{team.description}</p>
                  </div>

                  {/* 操作按钮 */}
                  <div className="space-y-2 mb-6">
                    {!isMember && team.is_recruiting && (
                      <Button
                        onClick={handleJoinTeam}
                        className="w-full bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
                      >
                        <UserPlus className="w-4 h-4 mr-2" />
                        申请加入
                      </Button>
                    )}
                    {isMember && !isLeader && (
                      <Button
                        variant="outline"
                        onClick={handleLeaveTeam}
                        className="w-full border-red-500 text-red-400 hover:bg-red-500/10"
                      >
                        离开团队
                      </Button>
                    )}
                    {isLeader && (
                      <Button
                        variant="outline"
                        onClick={() => router.push(`/teams/${team.id}/settings`)}
                        className="w-full border-gray-600 text-white hover:bg-gray-700"
                      >
                        <Settings className="w-4 h-4 mr-2" />
                        团队设置
                      </Button>
                    )}
                    <div className="flex gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        className="flex-1 border-gray-600 text-white hover:bg-gray-700"
                      >
                        <MessageCircle className="w-4 h-4 mr-2" />
                        私信
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        className="flex-1 border-gray-600 text-white hover:bg-gray-700"
                      >
                        <Share2 className="w-4 h-4 mr-2" />
                        分享
                      </Button>
                    </div>
                  </div>

                  {/* 基本信息 */}
                  <div className="space-y-3">
                    <div className="flex items-center gap-2 text-gray-300">
                      <Users className="w-4 h-4" />
                      <span>{team.member_count}/{team.max_members} 成员</span>
                    </div>
                    {team.location && (
                      <div className="flex items-center gap-2 text-gray-300">
                        <MapPin className="w-4 h-4" />
                        <span>{team.location}</span>
                      </div>
                    )}
                    <div className="flex items-center gap-2 text-gray-300">
                      <Calendar className="w-4 h-4" />
                      <span>创建于 {new Date(team.created_at).toLocaleDateString("zh-CN")}</span>
                    </div>
                    {team.competition_name && (
                      <div className="flex items-center gap-2 text-gray-300">
                        <Trophy className="w-4 h-4" />
                        <span>{team.competition_name}</span>
                      </div>
                    )}
                  </div>

                  {/* 技能标签 */}
                  <div className="mt-6 pt-6 border-t border-gray-700">
                    <h3 className="text-white font-semibold mb-3">团队技能</h3>
                    <div className="flex flex-wrap gap-2">
                      {team.skills.map((skill) => (
                        <Badge key={skill} variant="secondary" className="bg-blue-500/20 text-blue-300">
                          {skill}
                        </Badge>
                      ))}
                    </div>
                  </div>

                  {/* 成就 */}
                  {team.achievements.length > 0 && (
                    <div className="mt-6 pt-6 border-t border-gray-700">
                      <h3 className="text-white font-semibold mb-3">团队成就</h3>
                      <div className="space-y-2">
                        {team.achievements.map((achievement, index) => (
                          <div key={index} className="flex items-center gap-2 text-gray-300">
                            <Star className="w-4 h-4 text-yellow-400" />
                            <span className="text-sm">{achievement}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            </motion.div>
          </div>

          {/* 主要内容区域 */}
          <div className="lg:col-span-2">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2 }}
            >
              <Tabs defaultValue="members" className="w-full">
                <TabsList className="grid w-full grid-cols-3 bg-gray-800/50">
                  <TabsTrigger value="members" className="text-white">团队成员</TabsTrigger>
                  <TabsTrigger value="projects" className="text-white">项目</TabsTrigger>
                  <TabsTrigger value="activity" className="text-white">动态</TabsTrigger>
                </TabsList>

                <TabsContent value="members" className="mt-6">
                  <Card className="bg-gray-800/50 border-gray-700">
                    <CardHeader>
                      <CardTitle className="text-white">团队成员 ({team.members.length})</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      {team.members.map((member) => (
                        <div
                          key={member.id}
                          className="flex items-center justify-between p-4 bg-gray-700/30 rounded-lg hover:bg-gray-700/50 transition-colors"
                        >
                          <div className="flex items-center gap-4">
                            <Avatar className="w-12 h-12">
                              <AvatarImage src={member.avatar_url || ""} alt={member.username} />
                              <AvatarFallback className="bg-gradient-to-r from-blue-500 to-purple-500">
                                {member.username.charAt(0).toUpperCase()}
                              </AvatarFallback>
                            </Avatar>
                            <div>
                              <div className="flex items-center gap-2">
                                <h3 className="text-white font-semibold">
                                  {member.full_name || member.username}
                                </h3>
                                {getRoleIcon(member.role)}
                                <Badge variant="outline" className="text-xs border-gray-600 text-gray-300">
                                  {getRoleText(member.role)}
                                </Badge>
                              </div>
                              <p className="text-gray-400 text-sm">@{member.username}</p>
                              <div className="flex flex-wrap gap-1 mt-2">
                                {member.skills.slice(0, 3).map((skill) => (
                                  <Badge key={skill} variant="outline" className="text-xs border-gray-600 text-gray-400">
                                    {skill}
                                  </Badge>
                                ))}
                                {member.skills.length > 3 && (
                                  <Badge variant="outline" className="text-xs border-gray-600 text-gray-400">
                                    +{member.skills.length - 3}
                                  </Badge>
                                )}
                              </div>
                            </div>
                          </div>
                          <div className="flex items-center gap-2">
                            {member.email && (
                              <Button variant="ghost" size="sm" className="text-gray-400 hover:text-white">
                                <Mail className="w-4 h-4" />
                              </Button>
                            )}
                            {member.github_url && (
                              <Button variant="ghost" size="sm" className="text-gray-400 hover:text-white">
                                <Github className="w-4 h-4" />
                              </Button>
                            )}
                            {member.linkedin_url && (
                              <Button variant="ghost" size="sm" className="text-gray-400 hover:text-white">
                                <Linkedin className="w-4 h-4" />
                              </Button>
                            )}
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => router.push(`/users/${member.id}`)}
                              className="border-gray-600 text-white hover:bg-gray-700"
                            >
                              查看资料
                            </Button>
                          </div>
                        </div>
                      ))}
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent value="projects" className="mt-6">
                  <Card className="bg-gray-800/50 border-gray-700">
                    <CardHeader>
                      <CardTitle className="text-white">团队项目</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="text-center py-12">
                        <div className="text-6xl mb-4">💻</div>
                        <h3 className="text-xl font-semibold text-white mb-2">暂无项目</h3>
                        <p className="text-gray-300">团队还没有创建任何项目</p>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent value="activity" className="mt-6">
                  <Card className="bg-gray-800/50 border-gray-700">
                    <CardHeader>
                      <CardTitle className="text-white">团队动态</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="text-center py-12">
                        <div className="text-6xl mb-4">📝</div>
                        <h3 className="text-xl font-semibold text-white mb-2">暂无动态</h3>
                        <p className="text-gray-300">团队还没有发布任何动态</p>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>
              </Tabs>
            </motion.div>
          </div>
        </div>
      </div>
    </div>
  )
}